package com.lfy.modules.letter.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lfy.modules.common.domain.R;
import com.lfy.modules.common.domain.entity.UserEntity;
import com.lfy.modules.common.intercept.AuthHandlerInterceptor;
import com.lfy.modules.letter.domain.FeedLetterEntity;
import com.lfy.modules.letter.domain.GlobalLetterEntity;
import com.lfy.modules.letter.domain.SiteLetterEntity;
import com.lfy.modules.letter.domain.builder.Letter;
import com.lfy.modules.letter.domain.builder.LetterEnum;
import com.lfy.modules.letter.domain.dto.FeedLetterDTO;
import com.lfy.modules.letter.domain.dto.GlobalLetterDTO;
import com.lfy.modules.letter.domain.dto.LetterDTO;
import com.lfy.modules.letter.domain.event.LetterEvent;
import com.lfy.modules.letter.domain.vo.FeedLetterVO;
import com.lfy.modules.letter.domain.vo.GlobalLetterVO;
import com.lfy.modules.letter.domain.vo.LetterVO;
import com.lfy.modules.letter.domain.vo.SysLetterVO;
import com.lfy.modules.letter.service.SiteLetterService;
import com.lfy.modules.letter.mapper.SiteLetterMapper;
import com.lfy.modules.letter.service.SysFeedLetterService;
import com.lfy.modules.letter.service.SysGlobalLetterService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
* @author 吕飞扬
* @description 针对表【sys_site_letter】的数据库操作Service实现
* @createDate 2024-05-23 13:26:13
*/
@Service
public class SiteLetterServiceImpl extends ServiceImpl<SiteLetterMapper, SiteLetterEntity>
    implements SiteLetterService {
    @Resource
    private SysGlobalLetterService globalLetterService;
    @Resource
    private ThreadPoolExecutor mainThreadPool;
    @Resource
    private SysFeedLetterService feedLetterService;
    @Override
    public R<SysLetterVO> getLetterList() {
        SysLetterVO sysLetterVO = new SysLetterVO();
        UserEntity user = AuthHandlerInterceptor.authLocal.get();
        Integer letterCount = this.baseMapper.selectCount(new LambdaQueryWrapper<SiteLetterEntity>().eq(SiteLetterEntity::getReceiveId, user.getId()));
        sysLetterVO.setLetterCount(letterCount);
        List<SiteLetterEntity> siteLetterEntities = this.baseMapper.selectList(new LambdaQueryWrapper<SiteLetterEntity>()
                .eq(SiteLetterEntity::getReceiveId, user.getId()).orderByDesc(SiteLetterEntity::getCreateTime).last("limit 10"));
        if (siteLetterEntities != null && siteLetterEntities.size() > 0) {
            List<LetterVO> collect = siteLetterEntities.stream().map(item -> {
                LetterVO letterVO = new LetterVO();
                BeanUtils.copyProperties(item, letterVO);
                letterVO.setCreateTime(DateUtil.formatDateTime(item.getCreateTime()));
                return letterVO;
            }).collect(Collectors.toList());
            sysLetterVO.setLetterVOList(collect);
            mainThreadPool.execute(() -> {
                Set<Long> ids = collect.stream().map(LetterVO::getId).collect(Collectors.toSet());
                SiteLetterEntity siteLetterEntity = new SiteLetterEntity();
                siteLetterEntity.setIsRead(LetterEnum.ReadType.READ.getCode());
                this.update(siteLetterEntity,new LambdaQueryWrapper<SiteLetterEntity>()
                        .eq(SiteLetterEntity::getReceiveId, user.getId()).in(SiteLetterEntity::getId, ids));
            });


        }
        int count = globalLetterService.count(new LambdaQueryWrapper<GlobalLetterEntity>().eq(GlobalLetterEntity::getCreateBy, user.getId()));
        sysLetterVO.setGlobalLetterCount(count);
        List<GlobalLetterEntity> list = globalLetterService.list(new LambdaQueryWrapper<GlobalLetterEntity>().orderByDesc(GlobalLetterEntity::getCreateTime).last("limit 10"));
        if (list != null && list.size() > 0) {
            List<GlobalLetterVO> collect = list.stream().map(item -> {
                GlobalLetterVO globalLetterVO = new GlobalLetterVO();
                BeanUtils.copyProperties(item, globalLetterVO);
                if(item.getCreateBy().equals(user.getId())){
                    globalLetterVO.setCreateName("本条站内信由你发出");
                }
                globalLetterVO.setCreateTime(DateUtil.formatDateTime(item.getCreateTime()));
                return globalLetterVO;
            }).collect(Collectors.toList());
            sysLetterVO.setGlobalLetterVOList(collect);
        }
        return R.success(sysLetterVO);
    }

    @Override
    public R<List<LetterVO>> getSysLetter(Integer length) {
        SysLetterVO sysLetterVO = new SysLetterVO();
        UserEntity user = AuthHandlerInterceptor.authLocal.get();
        List<SiteLetterEntity> siteLetterEntities = this.baseMapper.selectList(new LambdaQueryWrapper<SiteLetterEntity>()
                .eq(SiteLetterEntity::getReceiveId, user.getId()).orderByDesc(SiteLetterEntity::getCreateTime).last("limit "+length+","+ "10"));
        if (CollectionUtils.isEmpty(siteLetterEntities)) {
            return R.success();
        }
            List<LetterVO> collect = siteLetterEntities.stream().map(item -> {
                LetterVO letterVO = new LetterVO();
                BeanUtils.copyProperties(item, letterVO);
                letterVO.setCreateTime(DateUtil.formatDateTime(item.getCreateTime()));
                return letterVO;
            }).collect(Collectors.toList());
            sysLetterVO.setLetterVOList(collect);
        mainThreadPool.execute(() -> {
            Set<Long> ids = collect.stream().map(LetterVO::getId).collect(Collectors.toSet());
            SiteLetterEntity siteLetterEntity = new SiteLetterEntity();
            siteLetterEntity.setIsRead(LetterEnum.ReadType.READ.getCode());
            this.update(siteLetterEntity,new LambdaQueryWrapper<SiteLetterEntity>()
                    .eq(SiteLetterEntity::getReceiveId, user.getId()).in(SiteLetterEntity::getId, ids));
        });
        return R.success(collect);
    }

    @Override
    public R<List<GlobalLetterVO>> getGlobalLetter(Integer length) {
        UserEntity user = AuthHandlerInterceptor.authLocal.get();
        List<GlobalLetterEntity> list = globalLetterService.list(new LambdaQueryWrapper<GlobalLetterEntity>().orderByDesc(GlobalLetterEntity::getCreateTime).last("limit " + length + "," + " 10"));
        if (CollectionUtils.isEmpty(list)) {
            return R.success();
        }

        List<GlobalLetterVO> collect = list.stream().map(item -> {
            GlobalLetterVO globalLetterVO = new GlobalLetterVO();
            BeanUtils.copyProperties(item, globalLetterVO);
            if (item.getCreateBy().equals(user.getId())) {
                globalLetterVO.setCreateName("本条站内信由你发出");
            }
            globalLetterVO.setCreateTime(DateUtil.formatDateTime(item.getCreateTime()));
            return globalLetterVO;
        }).collect(Collectors.toList());
        return R.success(collect);
    }

    @Override
    public R<Void> sendGlobalLetter(GlobalLetterDTO globalLetterDTO) {
        GlobalLetterEntity globalLetterEntity = new GlobalLetterEntity();
        globalLetterEntity.setCreateBy(AuthHandlerInterceptor.authLocal.get().getId());
        globalLetterEntity.setSubject(globalLetterDTO.getSubject());
        globalLetterEntity.setContent(globalLetterDTO.getContent());
        globalLetterEntity.setIsUrgent(globalLetterDTO.getIsUrgent());
        globalLetterEntity.setCreateName(AuthHandlerInterceptor.authLocal.get().getName());
        globalLetterEntity.setIsSendEmail(globalLetterDTO.getIsSendEmail());
        if(globalLetterDTO.getIsSendEmail().equals(LetterEnum.SendEmailType.YES.getCode())){
            //TODO 遍历用户发送邮件
        }
        globalLetterService.save(globalLetterEntity);

        return R.success();
    }

    @Override
    public R<Void> sendSysLetter(LetterDTO dto) {
        SiteLetterEntity siteLetterEntity = Letter.builder(LetterEnum.LetterType.SITE_SEND.getCode(), dto.getSubject(), dto.getContent(), dto.getReceiveId(), dto.getIsSendEmail());
        SpringUtil.publishEvent(new LetterEvent(this, siteLetterEntity));
        return R.success();
    }

    @Override
    public R<Void> sendFeedbackLetter(FeedLetterDTO dto) {
        FeedLetterEntity feedLetterEntity = new FeedLetterEntity();
        feedLetterEntity.setCreateBy(AuthHandlerInterceptor.authLocal.get().getId());
        feedLetterEntity.setSubject(dto.getSubject());
        feedLetterEntity.setContent(dto.getContent());
        feedLetterEntity.setCreateEmail(AuthHandlerInterceptor.authLocal.get().getUsername());
        feedLetterService.save(feedLetterEntity);
        return R.success();
    }

    @Override
    public R<List<FeedLetterVO>> getFeedbackLetter() {
        List<FeedLetterEntity> list = this.feedLetterService.list(new LambdaQueryWrapper<FeedLetterEntity>().orderByDesc(FeedLetterEntity::getCreateTime));
        if(CollectionUtils.isEmpty(list)){
            return R.success();
        }
        List<FeedLetterVO> result = list.stream().map(item -> {
            FeedLetterVO feedLetterVO = new FeedLetterVO();
            BeanUtils.copyProperties(item, feedLetterVO);
            feedLetterVO.setCreateTime(DateUtil.formatDateTime(item.getCreateTime()));
            return feedLetterVO;
        }).collect(Collectors.toList());
        return R.success(result);
    }

    /**
     * 清空全部反馈
     * @return R
     */
    @Override
    public R<Void> removeFeedbackLetter() {
        this.feedLetterService.remove(null);
        return R.success();
    }
}




